import React, { Fragment } from 'react'
import { InputNumber, Button } from 'antd';

export default function HooksDemo({ root }) {
  const [value1, setValue1] = React.useState(0);
  const [value2, setValue2] = React.useState(0);
  const [total, setTotal] = React.useState(0);
  const [count, setCount] = React.useState(0);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const timer = setInterval(() => {
      setCount(val => val + 1);
    }, 1000);

    // 卸载组件时调用
    return () => {
      clearInterval(timer);
    }
  }, []);

  function add() {
    // 直接赋值
    setTotal(value1 + value2);
    // 函数式
    // setTotal(() => value1 + value2);
  }

  function unmount() {
    root.unmount();
  }

  function showInputContent() {
    alert(inputRef.current.value);
  }

  return (
    <Fragment key="hooks">
      <h2>加法</h2>
      <InputNumber value={value1} onChange={ val => setValue1(val) } /> +
      <InputNumber value={value2} onChange={ val => setValue2(val) } />
      <Button type="link" onClick={add}>=</Button>
      {total}
      <hr />
      <h2>计时器</h2>
      {count}
      <hr />
      <Button onClick={unmount}>卸载组件</Button>
      <hr />
      <input ref={inputRef} />
      <Button onClick={showInputContent}>点击显示输入内容</Button>
    </Fragment>
  );
}
